const fse = require("fs-extra");
const path = require("path");
/**
 * 监听文件变化
 */
class WatchFile {
	/**
	 * 初始化
	 * @param {*} file
	 * @param {*} change
	 */
	constructor({
		file = null,
		change = () => {},
		err = () => {},
		close = () => {},
	}) {
		this.file = file;
		this.change = change;
		this.err = err;
		this.close = close;
		this.fileIsExist();
		this.fsWatcher = this.watchFile();
		this.initListener();
	}
	/**
	 * 文件是否存在 如果不存在就创建
	 */
	fileIsExist() {
		fse.ensureFileSync(this.file);
	}
	/**
	 * 监听文件
	 */

	watchFile() {
        console.log('watchFile');
		return fse.watch(this.file);
	}
	/**
	 * 初始化监听
	 */
	initListener() {
		this.fsWatcher.addListener("change", (event, filename) => {
            console.log(event);
			let filBody = null;
			if (path.extname(this.file) === ".json") {
				filBody = this.jsonFileRead();
			}
			this.change(event, filename, filBody);
		});
		this.fsWatcher.addListener("close", () => {
			this.close();
		});
		this.fsWatcher.addListener("error", () => {
			this.err();
		});
	}
	/**
	 * 关闭fsWacther
	 */
	closeFileWatcher() {
		this.fsWatcher.close();
	}
	/**
	 * 读取JSON文件
	 */
	jsonFileRead() {
		return fse.readJSONSync(this.file);
	}
}

module.exports = WatchFile;
